import {ref} from 'vue';
import {fileUploadAPI} from "@/api/fileUpload.js";

export function useFileSelect() {
  const selectedFile = ref(null);
  const accept = ref('.jpg,.png,.jpeg')
  const fileType = ref(1)

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      selectedFile.value = file
    }
  }

  const triggerFileSelect = (e, acceptType='', fType=1) => {
    fileType.value = fType
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = acceptType || accept.value;
    fileInput.multiple = false
    fileInput.onchange = handleFileChange;
    fileInput.click();
  }

  // 上传文件
  const uploadFile = async (File=null) => {
    const formData = new FormData();
    if(File){
      formData.append('file', File)
    }else{
      formData.append('file', selectedFile.value)
    }
    return await fileUploadAPI(formData)
  }

  return {
    fileType,
    selectedFile,
    triggerFileSelect,
    uploadFile
  }
}